package com.wuda.servlet.user;

import com.wuda.bean.User;
import com.wuda.dao.UserDao;
import com.wuda.utils.Util;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/user/updatePassword")
public class UpdatePassword extends HttpServlet {
	private static final long serialVersionUID = 1L;
	UserDao userDao = new UserDao();
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf8");

		PrintWriter out = response.getWriter();

		int userId = Integer.parseInt(request.getParameter("userId"));
		String oldPassword = request.getParameter("oldPassword");
		String newPassword = request.getParameter("newPassword");

		User user = userDao.getUserPasswordById(userId);

		JSONObject jsonResult = new JSONObject();
		if (user != null && Util.passMd5(oldPassword).equals(user.getPassword())) {
			boolean success = userDao.updatePassword(userId, newPassword);
			if (success) {
				HttpSession session = request.getSession();
				session.invalidate(); // 清除 session 数据

				jsonResult.put("code", 200);
				jsonResult.put("msg", "密码更新成功");
				jsonResult.put("url", request.getContextPath() + "/login.jsp");
			} else {
				jsonResult.put("code", 500);
				jsonResult.put("msg", "密码更新失败");
			}
		} else {
			jsonResult.put("code", 400);
			jsonResult.put("msg", "原密码错误");
		}

		out.print(jsonResult);
		out.flush();
	}





}
